package com.caseeye.model
import com.caseeye.base.{Entity, Versioning}
import com.caseeye.model.annotation.IdField
import com.caseeye.repository.CaseMasterRepository
import javax.annotation.Resource
import org.springframework.beans.factory.annotation._
import scala.reflect.BeanProperty

class CaseMaster extends Entity with Versioning {

    @BeanProperty
    var caseDetails = List[CaseDetail]()

    @BeanProperty
    var title = ""

    @BeanProperty
    var description = ""

    @BeanProperty
    @IdField
    var id = ""

    @BeanProperty
    @Resource
    var caseMasterRepository : CaseMasterRepository = null

    def addDetail(detail : CaseDetail) : List[CaseDetail] = {
        if (detail == null || detail == None) return caseDetails
        detail.setSeqNo(getMaxDetailSeqNo + 1)
        caseDetails = caseDetails :+ detail
        caseDetails
    }

    def removeDetail(detail : CaseDetail) : Boolean = {
        if (caseDetails.size == 0) return false
        val preSize = caseDetails.size
        caseDetails = caseDetails.filterNot((a : CaseDetail) => a.eq(detail))

        return caseDetails.size == preSize - 1
    }

    def +=(detail : CaseDetail) : List[CaseDetail] = addDetail(detail)

    def -=(detail : CaseDetail) : Boolean = removeDetail(detail)

    private def getMaxDetailSeqNo() : Int = { if (caseDetails.size > 0) caseDetails.reduceLeft((l, r) => if (l.getSeqNo > r.getSeqNo) l else r).getSeqNo else 0 }

    def save : Boolean = caseMasterRepository.save(this)

    def remove : Boolean = caseMasterRepository.remove(this)

}